package com.huayanginfo.saas.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.huayanginfo.saas.member.ThreadLocalJNDIURL;
import com.huayanginfo.saas.support.Constants;

/**
 * 对用户进行过滤，如果未登录，转到首页
 * @author rabbit
 *
 */
public class ThreadLocalJNDIUrlFilter implements Filter {
	private FilterConfig config;

	@Override
	public void destroy() {
		this.config = null;
	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String excludeNameSpace = config.getInitParameter("ExcludeNameSpace");
		String[] excludeNameSpaceStrings = excludeNameSpace.split(",");
		String servletPath = request.getServletPath();
		if (servletPath.length() != 0 && !servletPath.equals("/")
				&& !isNamespaceExclude(excludeNameSpaceStrings, servletPath)) {
			String jndiURL = (String) request.getSession().getAttribute(
					Constants.JNDIURLKEY);
			Object employee = request.getSession().getAttribute(Constants.USER);
			if (jndiURL == null || employee == null) {
				response.sendRedirect(request.getContextPath());
			} else {
				ThreadLocalJNDIURL.putJNDIURL(jndiURL);
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}

	}

	private boolean isNamespaceExclude(String[] excludeNameSpace,
			String servletPath) {
		boolean exclude = false;
		for (int i = 0; i < excludeNameSpace.length; i++) {
			if (servletPath.startsWith(excludeNameSpace[i])) {
				exclude = true;
				break;
			}
		}
		return exclude;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
	}

}
